<?php

/**
 *564654654654564
 * @author lovebing <lovebing365@126.com> Created on 2014-10-1 22:15:49
 */
class BaseActiveRecord extends CActiveRecord {

    public function beforeSave() {
        $now = date('Y-m-d H:i:s');
        if (parent::beforeSave()) {
            if ($this->isNewRecord && $this->hasAttribute('create_time')) {
                $this->create_time = $now;
            }
            if (!$this->isNewRecord && $this->hasAttribute('update_time')) {
                $this->update_time = $now;
            }
            return true;
        }
        return false;
    }

    /**
     * 
     * @return array
     */
    public function modelToArray() {
        return $this->getAttributes();
    }

    /**
     * 
     * @param array $modelList
     * @return array
     */
    public function modelListToAssocArray($modelList) {
        $res = array();
        foreach ($modelList as $model) {
            if (!is_a($model, 'CActiveRecord')) {
                continue;
            }
            $res[] = $model->modelToArray();
        }
        return $res;
    }

    public static function modelListtoAssocArrayList(array $modelList) {
        $res = array();
        foreach ($modelList as $model) {
            if (!is_a($model, 'CActiveRecord')) {
                continue;
            }
            $res[] = $model->modelToArray();
        }
        return $res;
    }

    /**
     * 
     * @param string $attribute
     * @return array
     */
    public function getErrors($attribute = null) {
        $errors = parent::getErrors($attribute);
        if (empty($errors)) {
            return $errors;
        }
        $labels = $this->attributeLabels();
        if (!is_null($attribute)) {
            if (!isset($labels[$attribute])) {
                return $errors;
            }
            foreach ($errors as $k => $v) {
                if ($v == '') {
                    continue;
                }
                $v = $labels[$attribute] . $v;
                $errors[$k] = $v;
            }
            return $errors;
        }
        foreach ($errors as $attr => $arr) {
            if (!isset($labels[$attr])) {
                continue;
            }
            $lableName = $labels[$attr];
            foreach ($arr as $k => $v) {
                if ($v == '') {
                    continue;
                }
                $arr[$k] = $lableName . $v;
            }
            $errors[$attr] = $arr;
        }

        return $errors;
    }

    /**
     * 
     * @return string
     */
    public function getErrorsString() {
        $errors = $this->getErrors();
        $res = array();
        foreach ($errors as $item) {
            $res[] = implode(',', $item);
        }
        return implode("\n", $res);
    }

}
